from typing import List
import pytest

from api.base_api import BasePrimeSpApi, BasePrimeAdminApi
from api.service_admin.admin_login_apis import PrimeAdminLoginApi
from api.service_sp.sp_login_apis import PrimeSpLoginApi
from common.db_uitl import DBUtil
from common.file_load import load_yaml_file
from common.logger import GetLogger


def pytest_collection_modifyitems(
        session: "Session", config: "Config", items: List["Item"]
) -> None:
    # item表示每个测试用例，解决用例名称中文显示问题
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode-escape")
        item._nodeid = item._nodeid.encode("utf-8").decode("unicode-escape")


@pytest.fixture(scope='session', autouse=True)
def aaget_logger():  # 注意这个worker_id是由pytest-xdist插件提供的，使用前必须先安装pytest-xdist
    GetLogger.get_logger()
    GetLogger.logger.info('日志对象初始化成功')


@pytest.fixture(scope='session', autouse=True)
def get_prime_admin_token():
    print("Admin!!!")
    username = load_yaml_file('/config/common.yml')['prime_admin']['primeName']
    pwd = load_yaml_file('/config/common.yml')['prime_admin']['primePassword']
    Primeadmin_login_api = PrimeAdminLoginApi(username, pwd)
    resp = Primeadmin_login_api.send()
    print(resp.json())
    BasePrimeAdminApi.prime_admin_token = resp.json()['result']['accessToken']


@pytest.fixture(scope='session', autouse=True)
def get_prime_sp_token():
    print("SP！！！")
    username = load_yaml_file('/config/common.yml')['prime_sp']['primeName']
    pwd = load_yaml_file('/config/common.yml')['prime_sp']['primePassword']
    Primesp_login_api = PrimeSpLoginApi(username, pwd)
    resp = Primesp_login_api.send()
    print(resp.json())
    BasePrimeSpApi.prime_sp_token = resp.json()['result']['accessToken']


@pytest.fixture(scope='session', autouse=False)
def db_connect():
    db_util = DBUtil(host=load_yaml_file('/config/db.yml')['test_db']['host'],
                     user=load_yaml_file('/config/db.yml')['test_db']['username'],
                     password=load_yaml_file('/config/db.yml')['test_db']['password'],
                     port=load_yaml_file('/config/db.yml')['test_db']["port"])
    yield db_util

    db_util.close()


if __name__ == '__main__':
    # gw0、gw1、gw2....gw10
    worker_id = 'gw100'
    print(int(worker_id[2:]))
